/*
 * @Description: 信息资料
 * @Author: ldx
 * @Date: 2022-09-17 21:22:28
 * @LastEditors: ldx
 * @LastEditTime: 2022-09-29 00:12:21
 */
import { UploadOutlined } from '@ant-design/icons'
import { useAntdTable, useRequest } from 'ahooks'
import {
  Button,
  Col,
  div,
  Form,
  Input,
  message,
  Modal,
  Popconfirm,
  Row,
  Table,
  Upload
} from 'antd'
const { TextArea } = Input
import moment from 'moment'
import { useState } from 'react'

import {
  createMaterial,
  deleteMaterial,
  downloadMaterial,
  queryDetails,
  queryMaterial,
  updateMaterial
} from '@/api/database/material'
import { TextTooltip } from '@/components'
import AuthButton from '@/components/authButton'
import { PageContainer } from '@/components/pageContainer'
const Material = () => {
  const [form] = Form.useForm()
  const [addForm] = Form.useForm()
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isModalOpenDetails, setIsModalOpenDetails] = useState(false)
  const [details, setDetails] = useState<any>()
  const [fileList, setFileList] = useState<any>([])
  /** 资料信息列表 */
  const { tableProps, search } = useAntdTable(queryMaterial, {
    form
  })

  /** 资料信息详情 */
  const { runAsync: runQueryDetails } = useRequest(queryDetails, {
    manual: true,
    onSuccess: (res) => {
      setDetails(res.data)
    }
  })
  /** 资料信息删除 */
  const { runAsync: runDeleteMaterial } = useRequest(deleteMaterial, {
    manual: true,
    onSuccess: () => {
      search.submit()
    }
  })
  /** 资料信息下载 */
  const { runAsync: runDownloadMaterial } = useRequest(downloadMaterial, {
    manual: true,
    onSuccess: (res) => {
      const filename = res.headers['content-disposition']
        .split(';')[1]
        .split('=')[1]
      // 创建隐藏的可下载链接
      const eleLink = document.createElement('a')
      eleLink.download = decodeURIComponent(filename)
      eleLink.style.display = 'none'
      // 字符内容转变成blob地址
      const blob = new Blob([res.data], { type: 'text/html' })
      eleLink.href = URL.createObjectURL(blob)
      // 触发点击
      document.body.appendChild(eleLink)
      eleLink.click()
      // 然后移除
      document.body.removeChild(eleLink)
    }
  })
  /** 创建资料信息 */
  const { runAsync: runCreateMaterial } = useRequest(createMaterial, {
    manual: true,
    onSuccess: () => {
      search.reset()
      setIsModalOpen(false)
      addForm.resetFields()
      setDetails(undefined)
      message.success('创建成功')
    }
  })
  /** 更新资料信息 */
  const { runAsync: runUpdateMaterial } = useRequest(updateMaterial, {
    manual: true,
    onSuccess: () => {
      search.reset()
      setIsModalOpen(false)
      addForm.resetFields()
      setDetails(undefined)
      message.success('更新成功')
    }
  })
  const columns: any[] = [
    {
      title: '序号',
      width: 60,
      align: 'center',
      dataIndex: 'a',
      render: (text: string, record: any, index: number) => {
        return <span>{index + 1}</span>
      }
    },
    {
      title: '标题',
      align: 'center',
      dataIndex: 'title'
    },
    {
      title: '摘要',
      align: 'center',
      ellipsis: true,
      dataIndex: 'description'
    },
    {
      title: '文档名称',
      align: 'center',
      ellipsis: true,
      dataIndex: 'fileName'
    },
    {
      title: '文档路径',
      align: 'center',
      ellipsis: true,
      dataIndex: 'filePath'
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'createTime',
      render: (text: string) => {
        return <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>
      }
    },
    {
      title: '创建人',
      align: 'center',
      dataIndex: 'creatorName'
    },
    {
      title: '操作',
     width:300,
      align: 'center',
      key: 'action',
      render: (text: number, record: any) => (
        <div>
          <AuthButton
            auth={['/**', '/material/**', '/material/details/{id}']}
            type="link"
            onClick={() => {
              setIsModalOpenDetails(true)
              runQueryDetails(record.id)
            }}
          >
            详情
          </AuthButton>
          <Popconfirm
            title="确认下载?"
            onConfirm={() => runDownloadMaterial(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <AuthButton
              auth={['/**', '/material/**', '/material/download/{id}']}
              type="link"
            >
              {/* <a download href={`/ivr/material/download/${record.id}`}>
                下载
              </a> */}
              下载
            </AuthButton>
          </Popconfirm>
          <AuthButton
            type="link"
            auth={['/**', '/material/**', '/material/update']}
            onClick={() => {
              // setRole(record)
              addForm.setFieldsValue({
                ...record,
                file: {}
              })
              setIsModalOpen(true)
              setDetails(record)
              setFileList([
                {
                  uid: '1',
                  name: record.fileName,
                  status: 'done'
                }
              ])
            }}
          >
            编辑
          </AuthButton>

          <Popconfirm
            title="确认删除信息资料?"
            onConfirm={() => runDeleteMaterial(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <AuthButton
              auth={['/**', '/material/**', '/material/delete/{id}']}
              type="link"
            >
              删除
            </AuthButton>
          </Popconfirm>
        </div>
      )
    }
  ]
  return (
    <>
      <PageContainer>
        <div>
          <Form form={form}>
            <Row gutter={24}>
              <Col span={5}>
                <Form.Item name="keyword">
                  <Input placeholder="请输入" />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Button onClick={() => search.submit()} type="primary">
                  搜索
                </Button>
              </Col>
              <Col span={11} className="flex justify-end">
                <AuthButton
                  auth={['/**', '/material/**', '/material/create']}
                  onClick={() => setIsModalOpen(true)}
                  type="primary"
                >
                  创建
                </AuthButton>
              </Col>
            </Row>
          </Form>
          <Table
            columns={columns}
            scroll={{ x: 1400 }}
            rowKey={(record) => record.id}
            {...tableProps}
            pagination={{
              showTotal: (total, range) => {
                console.log('xxx', range)
                const num = Math.ceil(total / 10)
                return (
                  <span style={{ color: '#fff', marginRight: '10px' }}>
                    共{num}页/共{total}条结果
                  </span>
                )
              },
              ...tableProps.pagination
            }}
          />
        </div>
      </PageContainer>
      <Modal
        width={800}
        title="角色详情"
        visible={isModalOpenDetails}
        onOk={() => {
          setIsModalOpenDetails(false)
          setDetails(undefined)
        }}
        onCancel={() => {
          setIsModalOpenDetails(false)
          setDetails(undefined)
        }}
      >
        <div className="pl-20px details">
          <div>
            <span className="w-120px inline-block ">标题：</span>
            <span>{details?.title}</span>
          </div>
          <div>
            <span className="w-120px inline-block ">摘要：</span>
            <span className="inline-flex">
              <TextTooltip className="w-520px">
                {details?.description}
              </TextTooltip>{' '}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">文档名称：</span>
            <span className="inline-flex">
              <TextTooltip className="w-520px">{details?.fileName}</TextTooltip>{' '}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">文档路径：</span>
            <span className="inline-flex">
              <TextTooltip className="w-520px">{details?.filePath}</TextTooltip>
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">创建时间：</span>
            <span>
              {moment(details?.createTime).format('YYYY-MM-DD HH:mm:ss')}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">创建人：</span>
            <span>{details?.creatorName}</span>
          </div>
          <div>
            <span className="w-120px inline-block ">更新时间：</span>
            <span>
              {details?.updateTime
                ? moment(details?.updateTime).format('YYYY-MM-DD HH:mm:ss')
                : ''}
            </span>
          </div>
          <div>
            <span className="w-120px inline-block ">更新人：</span>
            <span>{details?.updateName}</span>
          </div>
        </div>
      </Modal>
      <Modal
        width={800}
        title={details ? '编辑信息资料' : '上传信息资料'}
        visible={isModalOpen}
        onOk={() => {
          if (details) {
            addForm.validateFields().then((values) => {
              runUpdateMaterial({
                ...details,
                ...values
              })
            })
          } else {
            addForm.validateFields().then((values) => {
              const formData = new FormData()
              formData.append('materialFile', values.file.file)
              formData.append('title', values.title)
              formData.append('description', values.description)
              runCreateMaterial(formData)
            })
          }
        }}
        onCancel={() => {
          setIsModalOpen(false)
          addForm.resetFields()
          setDetails(undefined)
        }}
      >
        <div>
          <Form
            name="register"
            initialValues={{
              prefix: '86'
            }}
            form={addForm}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Form.Item
              name="title"
              label="标题"
              rules={[{ required: true, message: '请输入标题' }]}
            >
              <Input></Input>
            </Form.Item>
            <Form.Item
              name="description"
              label="摘要"
              rules={[{ required: true, message: '请输入摘要' }]}
            >
              <TextArea rows={4}></TextArea>
            </Form.Item>
            {!details && (
              <Form.Item
                name="file"
                label="文件"
                rules={[{ required: true, message: '请上传文件' }]}
              >
                <Upload
                  className="basis-upload"
                  beforeUpload={(file) => {
                    setFileList([file])
                    return false
                  }}
                  fileList={fileList}
                  // customRequest={upload}
                  accept=".doc,.docx,.xlsx,.xls,.txt,.pdf,.ppt,.pptx,.xml,.md"
                  headers={{
                    authorization: 'authorization-text'
                  }}
                >
                  <Button icon={<UploadOutlined />}>上传</Button>
                </Upload>
              </Form.Item>
            )}
          </Form>
        </div>
      </Modal>
    </>
  )
}

export default Material
